package hr.dario.kosh.service;

import hr.dario.kosh.Location;
import hr.dario.kosh.database.DataBaseAdapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class LocationService extends Service {
	private final String TAG = "LOCATION SERVICE TAG";

	ArrayList<Location> restaurantLocations;
	private final IBinder locationServiceBinder;
	private DataBaseAdapter menuDbHelper;

	/**
	 * Constructor
	 */
	public LocationService() {
		locationServiceBinder = new LocalBinder();
	}

	/**
	 * Inhereted methods
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return locationServiceBinder;
	}

	/**
	 * Local class for binding from other calsses (like Naslovna)
	 */
	public class LocalBinder extends Binder {
		public LocationService getLocationService() {
			Log.i(TAG, "Returning the service");
			return LocationService.this;
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		/*
		 * try {
		 * 
		 * String myFeed = getString(fh.app4stud.mensa.R.string.my_feed); URL
		 * url = new URL(myFeed); Log.i(TAG, "url opend"); URLConnection
		 * connection = url.openConnection();
		 * 
		 * int responseCode = -1; HttpURLConnection httpConnection = null; int
		 * iRetry = 0;
		 * 
		 * while (iRetry < 10) { iRetry++; try { httpConnection =
		 * (HttpURLConnection) connection;
		 * httpConnection.setConnectTimeout(3000);
		 * httpConnection.setDoInput(true); httpConnection.connect();
		 * responseCode = httpConnection.getResponseCode(); } catch (IOException
		 * e) { e.printStackTrace(); responseCode = -1; } if (responseCode ==
		 * HttpURLConnection.HTTP_OK) { iRetry = 10; Log.i(TAG,
		 * "If it came to here web service is working"); InputStream in =
		 * httpConnection.getInputStream();
		 * 
		 * DocumentBuilderFactory documentBuilderFactory =
		 * DocumentBuilderFactory .newInstance(); DocumentBuilder
		 * documentBuilder = documentBuilderFactory .newDocumentBuilder();
		 * 
		 * Document dom = documentBuilder.parse(in); Element documentElement =
		 * dom.getDocumentElement();
		 * 
		 * addAllLocations(documentElement); else { iRetry = 10;
		 */
		/*
		Resources myResources = getResources();
		InputStream inputStream = myResources.openRawResource(R.raw.locations);
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder documentBuilder = null;
		try {
			documentBuilder = documentBuilderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Document document = null;
		try {
			document = documentBuilder.parse(inputStream);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Element documentElement = document.getDocumentElement();
		addAllLocations(documentElement);
		/**
		 * }
		 * 
		 * } catch (MalformedURLException e) { e.printStackTrace(); } catch
		 * (IOException e) { e.printStackTrace(); } catch
		 * (ParserConfigurationException e) { e.printStackTrace(); } catch
		 * (SAXException e) { e.printStackTrace(); } finally { }}
		 */

		return Service.START_NOT_STICKY;
	}

	/**
	 * Metoda za parsanje XML datoteke. Ovo cemo poslje zamjenit dobibvanjem
	 * metodom koja se spaja na server i dobavlja podatke.
	 * 
	 * @param documentElement
	 */
	private void addAllLocations(Element documentElement) {

		menuDbHelper.open();
		menuDbHelper.deleteTableLocations();

		Log.i(TAG, "In add all locations");
		NodeList nodeList = documentElement.getElementsByTagName("location");

		if (nodeList != null && nodeList.getLength() > 0) {

			for (int i = 0; i < nodeList.getLength(); i++) {
				Element location;
				location = (Element) nodeList.item(i);
				Element city = (Element) location.getElementsByTagName("city")
						.item(0);

				Element locationName = (Element) location.getElementsByTagName(
						"locationName").item(0);

				Log.i(TAG, "getting the node values to str and doubles");

				String _locationName = locationName.getFirstChild()
						.getNodeValue();

				Log.i(TAG, "inserting in location table: " + " | "
						+ _locationName);
				menuDbHelper.createInput(DataBaseAdapter.DATABASE_TABLE_LOC,
						_locationName, "");
				// createLocation( String loc_name, String city, String street,
				// int house_nr, int zip, float lat, float lon )

			}
		}
	}
}
